package com.erli.exchange.common.interceptor;

import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.erli.exchange.common.constant.ApiConstant;
import com.erli.exchange.common.context.ApiRequestContextFactory;
import com.erli.exchange.common.token.TokenManager;
import com.erli.exchange.core.beans.api.AuthException;
import com.erli.exchange.core.beans.api.ExceptionEnum;
import com.erli.exchange.core.util.RequestUtil;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import lombok.Getter;
import lombok.Setter;

@Component
public class DefaultInterceptor implements HandlerInterceptor {
	
	@Resource
	private TokenManager tokenManager;

	@Setter
	@Getter
	@Value("#{'${exchange.authcheck.exclude-request-uri}'.split(',')}")
	private Set<String> excludeRequestURISet;
	
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	
    	if (excludeRequestURISet.contains(request.getRequestURI())) {
    		return true;
    	}
    	
        //获取用户凭证
        String token = RequestUtil.getHttpHeaderValue(ApiConstant.AUTH_TOKEN);
        if (StrUtil.isEmpty(token)) {
        	throw new AuthException(ExceptionEnum.TOKEN_IS_NULL);
        }
        
        Claims claims = tokenManager.getClaimByToken(token);
        if (claims == null) {
        	throw new AuthException(ExceptionEnum.AUTH_FAILURE);
        }
        
        //Token已过期
        if (tokenManager.isTokenExpired(claims.getExpiration())) {
        	throw new AuthException(ExceptionEnum.AUTH_FAILURE);
        }
        
        String userId = claims.getSubject();
////        UserEntity userEntity = userService.findById(Integer.parseInt(userId));
////        if (userEntity == null) {
////        	throw new AuthException(ExceptionEnum.AUTH_FAILURE);
////        }
    	//获取Token、用户ID
        ApiRequestContextFactory.createApiRequestContext(token, Integer.parseInt(userId));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
